<template>
  <div class="ai-chat-page wechat">
    <div class="chat-card">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <button class="chip-btn" @click="clearChat" aria-label="新会话">新会话</button>
        <div class="header-title" aria-label="对话标题">技术问问</div>
      </div>

      <!-- 聊天列表 -->
      <div ref="listRef" class="chat-list">
        <div v-for="(msg, idx) in messages" :key="idx" class="chat-item" :class="msg.role">
          <!-- <div class="avatar">{{ msg.role === 'user' ? '我' : 'AI' }}</div> -->
          <div class="bubble">
            <div class="content" v-html="renderMarkdownCached(msg, idx)"></div>
            <!-- 正在输入光标 -->
            <span v-if="running && idx === messages.length - 1 && msg.role === 'assistant'" class="cursor"></span>
            <!-- 操作按钮 -->
            <div v-if="msg.role === 'assistant' && !running && msg.content" class="msg-actions">
              <button class="action-btn" @click="copyMessage(msg.content)" aria-label="复制">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                  <path d="M9 9H17C18.1046 9 19 9.89543 19 11V19C19 20.1046 18.1046 21 17 21H9C7.89543 21 7 20.1046 7 19V11C7 9.89543 7.89543 9 9 9Z" stroke="currentColor" stroke-width="1.5"/>
                  <path d="M7 15H6C4.89543 15 4 14.1046 4 13V6C4 4.89543 4.89543 4 6 4H13C14.1046 4 15 4.89543 15 6V7" stroke="currentColor" stroke-width="1.5"/>
                </svg>
              </button>
            </div>
          </div>
        </div>

        
      </div>

      <!-- 输入区域 -->
      <div class="chat-input">
        <van-field v-model="input" rows="2" autosize type="textarea" placeholder="请输入问题..."
          @keyup.enter.exact="handlePrimaryClick" />
        <div class="actions">
          <van-button size="small" class="btn-primary" :type="running ? 'danger' : 'primary'"
            @click="handlePrimaryClick" :disabled="!running && !input.trim()">
            {{ running ? '停止' : '发送' }}
          </van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick, onBeforeUnmount } from 'vue';
import { showFailToast, showToast } from 'vant';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';

// 聊天消息列表
const messages = ref([
  { role: 'assistant', content: '您好，我是慢牛电控AI助手，专注于控制器专业解答与疑难问题处理。请问有什么可以帮您？' }
]);

const input = ref('');
const running = ref(false);
let ws = null;
let typeTimer = null;
const typingSpeed = 20; 
const CHUNK_SIZE_BASE = 6; 
let endReceived = false; 
let lastMdRenderAt = 0; 

// 滚动到底部
const listRef = ref(null);
function scrollToBottom() {
  nextTick(() => {
    const el = listRef.value;
    if (el) el.scrollTop = el.scrollHeight;
  });
}
watch(() => messages.value.length, () => scrollToBottom());

const SYSTEM_RULES = `你是慢牛电控AI助手，专注于控制器专业解答与疑难问题处理。`;

function buildMessagesForSpark() {
  const sys = { role: 'system', content: SYSTEM_RULES };
  const rest = messages.value.map(m => ({ role: m.role, content: m.content }));
  return [sys, ...rest];
}

// 身份固定回复
function getIdentityReply() {
  return '我是慢牛电控AI助手，专注于控制器相关问题的专业解答与疑难杂症解决。';
}

function isIdentityQuery(text) {
  const s = String(text || '')
    .trim()
    .replace(/[\s。．.！!？?]/g, '');
  // 常见问法：你是谁 / 你是? / 你是什么 / 你是
  return /^(你是(谁|什么)?|你是谁|你是什么)$/.test(s);
}

// 建立 WebSocket 连接并发送请求
function connectAndSend() {
  const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
  const url = `${protocol}://${location.host}/ws/spark`;
  ws = new WebSocket(url);

  ws.onopen = () => {
    const payload = { messages: buildMessagesForSpark() };
    ws.send(JSON.stringify(payload));
  };

  ws.onmessage = (ev) => {
    try {
      const data = JSON.parse(ev.data);
      if (data.type === 'started') return;
      if (data.type === 'delta') {
        const last = messages.value[messages.value.length - 1];
        if (last && last.role === 'assistant') {
          if (last.buffer === undefined) last.buffer = '';
          last.buffer += data.content || '';
          ensureTypeTimer();
        }
      } else if (data.type === 'end') {
        endReceived = true;
        ws?.close();
      } else if (data.type === 'error') {
        running.value = false;
        ws?.close();
        showFailToast(data.message || '服务异常');
      }
    } catch (e) {
      console.error('解析消息失败:', e);
    }
  };

  ws.onerror = () => {
    running.value = false;
    showFailToast('连接失败');
  };

  ws.onclose = () => {
    if (!endReceived) {
      running.value = false;
      clearTypeTimer();
      const last = messages.value[messages.value.length - 1];
      if (last && last.role === 'assistant') last.buffer = '';
    }
  };
}

// 发送消息
function send() {
  if (!input.value.trim() || running.value) return;
  const userText = input.value;
  messages.value.push({ role: 'user', content: userText });
  if (isIdentityQuery(userText)) {
    messages.value.push({ role: 'assistant', content: getIdentityReply() });
    input.value = '';
    running.value = false;
    return;
  }
  messages.value.push({ role: 'assistant', content: '', buffer: '' });
  input.value = '';
  running.value = true;
  endReceived = false;
  connectAndSend();
}

// 停止生成
function stop() {
  if (ws && running.value) {
    ws.close();
    running.value = false;
    clearTypeTimer();
    // 清空缓冲
    const last = messages.value[messages.value.length - 1];
    if (last && last.role === 'assistant') last.buffer = '';
  }
}

// 主按钮点击
function handlePrimaryClick() {
  if (running.value) {
    stop();
  } else {
    send();
  }
}

// 转义 HTML 防止 XSS
function escapeHtml(str) {
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

// markdown-it 渲染器（支持表格/换行/链接识别/高亮）
const md = new MarkdownIt({
  html: false,
  linkify: true,
  breaks: true,
  highlight(str, lang) {
    try {
      if (lang && hljs.getLanguage(lang)) {
        const v = hljs.highlight(str, { language: lang }).value;
        return `<pre class="code hljs"><code class="lang-${lang}">${v}</code></pre>`;
      }
    } catch (e) {
    }
    return `<pre class="code"><code>${escapeHtml(str)}</code></pre>`;
  }
});

function renderMarkdown(text) {
  if (!text) return '';
  return md.render(String(text));
}

function fastRender(text) {
  if (!text) return '';
  return escapeHtml(String(text)).replace(/\r?\n/g, '<br>');
}

// 带缓存与流式优化的渲染
function renderMarkdownCached(msg, idx) {
  const isStreaming = running.value && idx === messages.value.length - 1 && msg.role === 'assistant';
  if (isStreaming) {
    return msg._cacheHtml || fastRender(msg.content);
  }
  if (!msg) return '';
  if (msg._cacheContent !== msg.content) {
    msg._cacheHtml = renderMarkdown(msg.content || '');
    msg._cacheContent = msg.content;
  }
  return msg._cacheHtml || '';
}

// 复制消息
async function copyMessage(text) {
  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(text || '');
    } else {
      const ta = document.createElement('textarea');
      ta.value = text || '';
      ta.style.position = 'fixed';
      ta.style.left = '-9999px';
      document.body.appendChild(ta);
      ta.select();
      document.execCommand('copy');
      document.body.removeChild(ta);
    }
    showToast({ message: '已复制', duration: 1000 });
  } catch (e) {
    showFailToast('复制失败');
  }
}

// 清空会话
function clearChat() {
  messages.value = [{ role: 'assistant', content: '已清空，会话重新开始。' }];
}

// 组件卸载前关闭连接
onBeforeUnmount(() => {
  if (ws) ws.close();
  clearTypeTimer();
});

// 打字机渲染
function ensureTypeTimer() {
  if (typeTimer) return;
  typeTimer = setInterval(() => {
    const last = messages.value[messages.value.length - 1];
    if (!last || last.role !== 'assistant') return;
    if (last.buffer && last.buffer.length > 0) {
      const n = Math.max(CHUNK_SIZE_BASE, Math.min(24, Math.floor(last.buffer.length / 20)));
      last.content += last.buffer.slice(0, n);
      last.buffer = last.buffer.slice(n);
      scrollToBottom();
      const now = Date.now();
      if (now - lastMdRenderAt > 300) {
        last._cacheHtml = renderMarkdown(last.content || '');
        last._cacheContent = last.content;
        lastMdRenderAt = now;
      }
    } else if (endReceived) {
      running.value = false;
      clearTypeTimer();
      const html = renderMarkdown(last.content || '');
      last._cacheContent = last.content;
      last._cacheHtml = html;
      scrollToBottom();
    }
  }, typingSpeed);
}

function clearTypeTimer() {
  if (typeTimer) {
    clearInterval(typeTimer);
    typeTimer = null;
  }
}
</script>

<style scoped>
.ai-chat-page.wechat {
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
  box-sizing: border-box;
  position: relative;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial,
    'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;

}

.chat-card {
  width: 100%;
  max-width: 920px;
  background: rgba(255, 255, 255, 0.9);
  box-shadow: 0 12px 40px rgba(15, 23, 42, 0.08);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(224, 230, 240, 0.9);
  /* border-radius: 18px; */
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

/* 头部 */
.chat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  position: sticky;
  top: 0;
  z-index: 5;
  background: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border-bottom: 1px solid #eef2f7;
  box-shadow: 0 6px 16px -14px rgba(15, 23, 42, 0.28);
}

.chip-btn {
  border: 1px solid #d0d7e2;
  background: #fff;
  border-radius: 18px;
  padding: 6px 12px;
  font-size: 13px;
  color: #4a5568;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.chip-btn:hover {
  background: #f1f5f9;
  transform: translateY(-1px);
}

.header-title {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  font-size: 15px;
  font-weight: 600;
  color: #0f172a;
  letter-spacing: 0;
  pointer-events: none;
}

/* 聊天列表 */
.chat-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px 16px 28px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  scroll-behavior: smooth;
  /* background: linear-gradient(180deg, rgba(255,255,255,0.6), rgba(255,255,255,0.9)); */
  /* 渐变 + 网格纹理背景 */
  background:
    radial-gradient(ellipse at 20% 10%, rgba(7, 193, 96, 0.08), transparent 40%),
    radial-gradient(ellipse at 80% 0%, rgba(37, 99, 235, 0.08), transparent 40%),
    linear-gradient(180deg, #f7fafc, #eef2f7 20%, #eef2f7 80%, #f7fafc);
}

.chat-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.chat-item.user {
  flex-direction: row-reverse;
}


.chat-item.user .avatar {
  background: #07c160;
  color: #fff;
}

.typing-item {
  align-items: flex-end;
}

.avatar {
  flex: 0 0 30px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: linear-gradient(135deg, #e2e8f0, #cbd5e1);
  color: #334155;
  font-size: 12px;
  display: grid;
  place-items: center;
  box-shadow: 0 2px 6px rgba(15, 23, 42, 0.08);
  user-select: none;
}

.chat-item.user .avatar {
  background: linear-gradient(135deg, #22c55e, #16a34a);
  color: #fff;
}

/* 气泡 */
.bubble {
  max-width: 90%;
  min-width: 48px;
  padding:0px 10px;
  border-radius: 14px 14px 14px 6px;
  background: #ffffff;
  position: relative;
  box-shadow: 0 1px 6px rgba(15, 23, 42, 0.05);
  border: 1px solid #eef2f7;
  word-break: break-word;
  line-height: 1.6;
  box-sizing: border-box;
}

.chat-item.user .bubble {
  background: linear-gradient(135deg, #22c55e, #07c160);
  color: #fff;
  border: none;
  box-shadow: 0 4px 14px rgba(7, 193, 96, 0.25);
  border-radius: 14px 14px 6px 14px;
}

.typing-bubble {
  background: #f3f6fa;
  border-color: #e7edf5;
}

/* 气泡小三角 */
.bubble::before {
  content: '';
  position: absolute;
  top: 14px;
  left: -6px;
  width: 0;
  height: 0;
  border: 6px solid transparent;
  border-right-color: #ffffff;
}

.chat-item.user .bubble::before {
  left: auto;
  right: -6px;
  border-right-color: transparent;
  border-left-color: #07c160;
}

/* 内容 */
.content {
  width: auto;
  margin: 0;
  font-size: 13px;
  color: #2d3748;
  line-height: 1.65;
  overflow: visible;
}

.chat-item.user .content {
  color: #ffffff;
}

/* 代码块 */
.content pre.code {
  margin: 8px 0;
  background: #1a1f2e;
  color: #e0e6f0;
  border-radius: 10px;
  padding: 6px;
  overflow-x: auto;
  font-size: 14px;
  border: 1px solid #2a3142;
  box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.3);
  white-space: pre-wrap;
  word-break: break-word;
  overflow-wrap: anywhere;
  max-width: 100%;
  box-sizing: border-box;
  width: 100%;
  display: block;
}

.content code {
  background: #f1f3f5;
  color: #d73a49;
  border-radius: 6px;
  padding: 2px 6px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 0.95em;
  white-space: pre-wrap;
  word-break: break-word;
  overflow-wrap: anywhere;
}

.content pre.code code {
  background: transparent;
  padding: 0;
  color: inherit;
}

/* 表格（markdown-it 原生支持） */
.content table {
  width: 100%;
  border-collapse: collapse;
  margin: 8px 0;
  font-size: 13px;
  display: block;          /* 防止在小屏超出 */
  overflow-x: auto;        /* 表格横向滚动 */
  -webkit-overflow-scrolling: touch;
}

.content th,
.content td {
  border: 1px solid #e5e7eb;
  padding: 6px 8px;
  text-align: left;
  word-break: break-word;
  white-space: normal;
}

.content thead th {
  background: #f8fafc;
  color: #111827;
}

.content .hljs {
  background: transparent;
}

.content * {
  max-width: 100%;
}

/* 小屏适配，避免代码块撑破气泡 */
@media (max-width: 480px) {
  .bubble {
    max-width: 82%;
  }
  .content pre.code {
    font-size: 12px;
    padding: 10px;
  }
  .content table {
    font-size: 12px;
  }
}

.content a {
  color: #07c160;
  text-decoration: underline;
  word-break: break-all;
}

.content a:hover {
  opacity: 0.8;
}

.content strong {
  font-weight: 600;
  color: #1a1a1a;
}

.content em {
  font-style: italic;
  color: #555;
}

/* 操作按钮 */
.msg-actions {
  position: absolute;
  right: -30px;
  bottom: -3px;
  display: flex;
  opacity: .6;
  justify-content: flex-end;
}

.action-btn {
  border: none;
  background: transparent;
  color: #718096;
  font-size: 13px;
  padding: 4px 8px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.action-btn:hover {
  color: #4a5568;
  background: #f7f8fa;
}

/* 正在输入提示 点点动画 */
.typing-bubble .dot {
  width: 6px;
  height: 6px;
  background: #94a3b8;
  border-radius: 50%;
  animation: bounce 1s infinite ease-in-out;
}

.typing-bubble .dot:nth-child(2) {
  animation-delay: .15s;
}

.typing-bubble .dot:nth-child(3) {
  animation-delay: .3s;
}

@keyframes bounce {

  0%,
  80%,
  100% {
    transform: translateY(0);
    opacity: .7;
  }

  40% {
    transform: translateY(-5px);
    opacity: 1;
  }
}

/* 输入区 */
.chat-input {
  display: grid;
  grid-template-columns: 1fr auto;
  align-items: center;
  border-top: 1px solid #e8edf1;
  box-shadow: 0 -8px 24px -10px rgba(15, 23, 42, 0.12);
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(8px);
}

:deep(.van-field) {
  background: #ffffff;
  border-radius: 14px;
}

:deep(.van-field__control) {
  padding: 12px 14px;
  border: 1px solid #e6eaf0;
  border-radius: 12px;
  font-size: 15px;
  color: #0f172a;
  resize: none;
  background: #ffffff;
  transition: border 0.2s, box-shadow .2s;
}

:deep(.van-field__control):focus {
  border-color: #2563eb;
  outline: none;
  box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.12);
}

:deep(.van-field__control::placeholder) {
  color: #a0aec0;
}

.actions {
  display: flex;
  justify-content: flex-end;
}

/* 发送按钮 */
.btn-primary {
  background: #2563eb;
  border-color: #2563eb;
  color: #fff;
  height: 60px;
  width: 78px;
  border-radius: 12px;
  margin: 0 4px 0 0;
  font-size: 15px;
  box-shadow: 0 8px 20px rgba(37, 99, 235, 0.22);
}

.btn-primary:hover {
  background: #1d4ed8;
  border-color: #1d4ed8;
  transform: translateY(-1px);
}

.btn-primary:disabled {
  border-radius: 12px;
  font-weight: 500;
  transition: all 0.2s ease;
  box-shadow: none;
  background: #94b3ff;
  border-color: #94b3ff;
}

.btn-primary:active {
  transform: translateY(1px);
  box-shadow: none;
}

/* 光标动画 */
.cursor {
  display: inline-block;
  width: 6px;
  height: 1.1em;
  background: #333;
  margin-left: 2px;
  animation: blink 1s step-start infinite;
}

@keyframes blink {
  50% {
    opacity: 0;
  }
}

/* 滚动条 */
.chat-list::-webkit-scrollbar {
  width: 6px;
}

.chat-list::-webkit-scrollbar-track {
  background: transparent;
}

.chat-list::-webkit-scrollbar-thumb {
  background: rgba(148, 163, 184, 0.3);
  border-radius: 3px;
}

.chat-list::-webkit-scrollbar-thumb:hover {
  background: rgba(148, 163, 184, 0.5);
}
</style>